package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.NorthSeaWaveMapper;
import com.xxl.job.executor.model.NorthSeaWave;
import com.xxl.job.executor.utils.CmUtil;
import com.xxl.job.executor.utils.ConstUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;

/*
"海洋（浪高）数据抓取";
 */
@Component
public class SeaWaveTask {

    private static Logger logger = LoggerFactory.getLogger(SeaWaveTask.class);


    private String taskContents;
    @Autowired
    private ConstUtil constUtil;
    @Autowired
    private NorthSeaWaveMapper northSeaWaveMapper;

    @XxlJob(value = "SeaWaveTask",init = "init", destroy = "destroy")
    public ReturnT<String> SeaWaveTask(String param) throws Exception {
//
//        if (constUtil == null) {
//            constUtil = SpringContextHolder.getBean(ConstUtil.class);
//        }
//        if (northSeaWaveMapper == null) {
//            northSeaWaveMapper  = SpringContextHolder.getBean(NorthSeaWaveMapper.class);
//        }
        // 获取文本内容
        Document doc = getHtml(constUtil);
        if (doc == null) {
            System.out.println("kong");
        };
        // 获取浪高数据
        Elements elements = doc.select("[class=ul1]").last().select("li");
        for (Element element:elements) {
            String seaName = element.text().substring(0,4);
            if (seaName.indexOf("渤")>=0) {  // 渤  海
                seaName = "渤  海";
            }else if (seaName.indexOf("北")>=0) {    // 黄海北部
                seaName = "黄海北部";
            }else if (seaName.indexOf("中")>=0) {    // 黄海中部
                seaName = "黄海中部";
            }else if (seaName.indexOf("青")>=0) {    // 青岛近海
                seaName = "青岛近海";
            }

            // 获取浪高
            String waveHigh = element.select("span").text()
                    .substring(2,element.select("span").text().indexOf("米"));
            ArrayList<String> waveList = new ArrayList<>();
            waveList.add(seaName);
            waveList.add(waveHigh);
            NorthSeaWave northSeaWave;
            String publishDate = CmUtil.date2day(null);
            // 根据发布时间判断各海域当天海浪数据是否存在
            northSeaWave = northSeaWaveMapper.selectByPublishDateAndSeaName(publishDate,seaName);
            if(northSeaWave==null){
                // 不存在，插入一条数据
                try {
                    northSeaWave = new NorthSeaWave();
                    northSeaWave.setNorthSeaWaveId(CmUtil.getUUID());
                    northSeaWave.setCreateTime(CmUtil.date2db(null));
                    // 发布时间
                    northSeaWave.setPublishDate(publishDate);
                    // 海域名称
                    northSeaWave.setSeaName(seaName);
                    // 浪高
                    northSeaWave.setWaveHeight(waveHigh);
                    northSeaWaveMapper.insertSelective(northSeaWave);
                    this.taskContents = "插入"+seaName+"  "+publishDate+"   浪高数据成功！";
                }catch (Exception e){
                    e.printStackTrace();
                    this.taskContents = "插入"+seaName+"  "+publishDate+"   浪高数据异常！";
                }
            }
            else if(!northSeaWave.toString().equals(waveList.toString())){
                try {
                    // 更新已有数据
                    northSeaWave.setSeaName(seaName);
                    northSeaWave.setWaveHeight(waveHigh);
                    northSeaWaveMapper.updateByPrimaryKeySelective(northSeaWave);
                    this.taskContents = "更新"+seaName+"  "+publishDate+"   浪高数据成功！";
                }catch (Exception e){
                    e.printStackTrace();
                    this.taskContents = "更新"+seaName+"  "+publishDate+"   浪高数据异常！";
                }
            }
        }
        return ReturnT.SUCCESS;
    }
    /**
     * 获取HTML内容
     *
     * @param constUtil
     * @return
     */
    public static Document getHtml(ConstUtil constUtil) {
        Document doc = null;
        try {
            if (constUtil.useProxy) {
                // 设置代理
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(constUtil.proxyId, constUtil.proxyPort));
                doc = Jsoup.connect(constUtil.seaWaveUrl)
                        .proxy(proxy)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            } else {
                doc = Jsoup.connect(constUtil.seaWaveUrl)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }
    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destory");
    }
}
